package com.cyh.forum.services.impl;

import com.cyh.forum.common.AppResult;
import com.cyh.forum.common.ResultCode;
import com.cyh.forum.dao.ArticleMapper;
import com.cyh.forum.dao.BoardMapper;
import com.cyh.forum.dao.UserMapper;
import com.cyh.forum.exception.ApplicationException;
import com.cyh.forum.model.Article;
import com.cyh.forum.model.Board;
import com.cyh.forum.model.User;
import com.cyh.forum.services.IArticleService;
import com.cyh.forum.services.IBoradService;
import com.cyh.forum.services.IUserService;
import com.cyh.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.crypto.spec.RC2ParameterSpec;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    //  版块和用户 的操作
    @Resource
    private IBoradService iBoradService;
    @Resource
    private IUserService iUserService;


    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private BoardMapper boardMapper;


    @Override
    public void create(Article article) {
        //  参数校验
        if (article == null
                || article.getUserId() == null
                || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //  设置 帖子默认值
        article.setVisitCount(0);   //  帖子浏览数
        article.setReplyCount(0);   //  帖子回复数
        article.setLikeCount(0);   //  帖子点赞数
        article.setState((byte) 0);   //
        article.setDeleteState((byte) 0);   //
        Date date = new Date();
        article.setCreateTime(date);   //  发表时间
        article.setUpdateTime(date);   //  修改时间

        //  将 帖子 插入数据库
        int articleRow = articleMapper.insertSelective(article);
        //  校验插入结果
        if (articleRow <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + "帖子新增失败");
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //  获取用户信息
        User user = iUserService.selectById(article.getUserId());
        //  校验用户是否存在
        if (user == null){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", 发帖失败 user id = " + article.getUserId());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //  更新用户发帖数
        iUserService.addOneArticleCountById(user.getId());


        //  获取版块信息
        Board board = iBoradService.selectByPrimaryKey(article.getBoardId());
        //  校验版块是否存在
        if (board == null){
            //  打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString() + ", 发帖失败 board id = " + article.getBoardId());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //  更新版块发帖数
        iBoradService.addOneArticleCountById(board.getId());

        //  打印执行成功的日志
        log.info(ResultCode.SUCCESS.toString()
                + " ,user id = " + article.getUserId()
                + " ,board id = " + article.getBoardId()
                + " ,article id = " + article.getId());

        //  throw new ApplicationException(AppResult.failed("测试事务回滚"));
    }

    @Override
    public List<Article> selectAll() {
         List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //  非空校验
        if (boardId == null || boardId <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  校验版块是否为空
        Board board = boardMapper.selectByPrimaryKey(boardId);
        if (board == null){
            //  打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //  根据版块id 获取所有帖子
        List<Article> articles = articleMapper.selectByBoardId(boardId);
        return articles;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //  非空校验
        if(userId == null || userId <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  校验用户是否存在
        val user = iUserService.selectById(userId);
        if (user == null || user.getDeleteState() != 0){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //  调用DAO层
        val articles = articleMapper.selectByUserId(userId);
        //  返回结果
        return articles;
    }

    @Override
    public Article selectById(Long id) {
        //  参数非空校验
        if (id == null || id <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  调用DAO层获取结果
        val article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public Article selectDetailById(Long id) {
        //  参数非空校验
        if (id == null){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  调用DAO层获取结果
        Article result = articleMapper.selectDetailById(id);
        //  校验结果
        if (result == null){
            //  打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //  创建一个更新对象
        Article update = new Article();
        update.setId(result.getId());
        update.setVisitCount(result.getVisitCount() + 1);
        //  更新数据库中的访问数据
        int row = articleMapper.updateByPrimaryKeySelective(update);
        //  校验是否更新成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + "帖子id articleID = " + result.getId());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //  对已查询的result的访问数据也进行更新
        result.setVisitCount(result.getVisitCount() + 1);
        return result;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //  非空校验
        if (id == null

                || StringUtil.isEmpty(title)
                || StringUtil.isEmpty(content)){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //  设置更新对象
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        //  更新编辑时间
        article.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(article);
        //  校验更新是否成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED_UPDATE.toString() + "articleID = " + id);
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE));
        }

    }

    @Override
    public void thumbsUpById(Long id) {
        //  非空校验
        if (id == null || id <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  获取帖子原始数据
        Article article = articleMapper.selectByPrimaryKey(id);
        //  校验帖子是否存在
        if (article == null || article.getDeleteState() == 1){
            //  打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //  设置更新对象
        Article update = new Article();
        update.setId(id);
        update.setLikeCount(article.getLikeCount() + 1);
        //  调用DAO层
        val row = articleMapper.updateByPrimaryKeySelective(update);
        //  校验是否修改成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED_UPDATE.toString() + "articleID = " + id);
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE));
        }
        //  对当前页面显示的数据也进行修改
        article.setLikeCount(article.getLikeCount() + 1);
    }

    @Override
    public void deleteById(Long id) {
        //  非空校验
        if (id == null || id <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  校验帖子是否存在
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1){
            //  打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //  设置更新对象
        Article update = new Article();
        update.setId(id);
        update.setDeleteState((byte) 1); // 设置为删除状态
        //  调用DAO层
        val row = articleMapper.updateByPrimaryKeySelective(update);
        //  校验是否更新成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED_ARTICLE_DELETE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_DELETE));
        }
        //  更新版块的帖子数量
        iBoradService.subOneArticleCountById(article.getBoardId());
        //  更新用户的帖子数量
        iUserService.subOneArticleCountById(article.getUserId());
        //  打印帖子删除成功日志
        log.info(MessageFormat.format("帖子删除成功, 帖子id={0},用户id={1}",id,article.getUserId()));
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //  非空校验
        if (id == null || id <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  校验帖子是否存在
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1){
            //  打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //  设置更新对象
        Article update = new Article();
        update.setId(id);
        update.setReplyCount(article.getReplyCount() + 1);
        val row = articleMapper.updateByPrimaryKeySelective(update);
        //  校验是否更新成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_REPLY_COUNT.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_REPLY_COUNT));
        }
    }



}









